package com.penglecode.nio.socket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class BufferUtils {

	public static byte[] read(SocketChannel client, ByteBuffer buffer){
		try {
			buffer.clear();
			client.read(buffer);
			byte[] datas = new byte[buffer.position()];
			//buffer.position(0);
			buffer.rewind();
			buffer.get(datas);
			return datas;
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		
	}
	
	public static void write(SocketChannel client, ByteBuffer buffer, byte[] datas){
		try {
			buffer.put(datas);
			buffer.flip();
			client.write(buffer);
			buffer.clear();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		
	}

}
